package com.example.retrofitdemo616lixiao.model;

import com.example.retrofitdemo616lixiao.bean.UserBean;
import com.example.retrofitdemo616lixiao.common.Common;
import com.example.retrofitdemo616lixiao.iface.LoginListener;
import com.example.retrofitdemo616lixiao.iface.Loginiface;
import com.example.retrofitdemo616lixiao.service.UserService;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class LoginModel implements Loginiface {
    private Retrofit retrofit;


    public LoginModel() {
        retrofit=new Retrofit.Builder()
                .baseUrl(Common.BASEURL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    @Override
    public void getLoginResult(String username, String password, final LoginListener loginListener) {
        UserService userService=retrofit.create(UserService.class);
        Call<UserBean> call=userService.login(username,password);
        call.enqueue(new Callback<UserBean>() {
            @Override
            public void onResponse(Call<UserBean> call, Response<UserBean> response) {
                if (response.isSuccessful()&&response.body()!=null&&response.body().getId()!=null){
                    loginListener.onResponse(response.body());
                }
                else loginListener.onFail("login fail");
            }

            @Override
            public void onFailure(Call<UserBean> call, Throwable t) {
                loginListener.onFail(t.getMessage());
            }
        });
    }
}
